package com.mmp.main.servlet.report.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.entity.Hospital;
import com.mmp.main.entity.HospitalDepartment;
import com.mmp.main.entity.LookupDeviceCategory;
import com.mmp.main.util.WebUtil;

@WebServlet(urlPatterns = { "/ViewDevicesByCatnDepSearch", "/ViewDevicesStatusSearch" })

public class DevicesByCatAndDepFilterDisplayServlet extends BasicServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		Hospital currentLocation = getSessionLocation(request);

		String reportType = WebUtil.getParamValue(request, "reportType", null);
		boolean ajaxRequest = (reportType != null && !reportType.isEmpty());

		if (ajaxRequest && (currentLocation == null || currentLocation.getHealthCenter()))
			return;

		if (currentLocation != null && !currentLocation.getHealthCenter()) {

			List<HospitalDepartment> hospDepList = dbQueryManager.getLocationDepartments(currentLocation.getId());

			if (ajaxRequest) {
				PrintWriter out = response.getWriter();
				out.println(getHospitalDepListAsJSONArray(hospDepList));
				return;
			} else
				request.setAttribute("depList", hospDepList);
		}

		request.setAttribute("catList", dbQueryManager.findAll(LookupDeviceCategory.class));
		forward(request, response, "report/filter/DevicesByDepAndCatFilter.jsp");
	}

	private JSONArray getHospitalDepListAsJSONArray(List<HospitalDepartment> depList) throws JSONException {
		JSONArray jsonArray = new JSONArray();
		for (HospitalDepartment dep : depList) {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("id", dep.getId());
			jsonObj.put("name", dep.getName());
			jsonArray.put(jsonObj);
		}
		return jsonArray;
	}

}
